package com.atguigu.lease.common.utils;

import com.atguigu.lease.common.excetion.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

import javax.crypto.SecretKey;
import java.util.Date;

/**
 * @author 芦博
 * @description json web token
 * @createDate 2025/11/7 12:23
 */
public class JwtUtils {

    private static Long tokenExpirationTime = 60 * 60 * 1000L;
    private static SecretKey key_secret = Keys.hmacShaKeyFor("hT8yC8cW8eV3kW0fL2vW0nL7rJ8yB5eJ".getBytes());

    //创建token
    public static String createToken(Long userId, String username) {
        String token = Jwts.builder()
                .setSubject("创建token")
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpirationTime))
                .claim("userId", userId)
                .claim("username", username)
                .signWith(key_secret)
                .compact();
        return token;
    }

    //解析token
    public static Claims parseToken(String token) {

        try {
            Claims payload_body = Jwts.parserBuilder()
                    .setSigningKey(key_secret)
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
            return payload_body;
        } catch (JwtException e) {
            throw new LeaseException(ResultCodeEnum.DATA_ERROR);
        }
    }
}
